const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

exports.main = async (event, context) => {
    const { tipId, action } = event
    const wxContext = cloud.getWXContext()

    try {
        // 更新tips集合中的点赞数
        const updateRes = await db.collection('tips').doc(tipId).update({
            data: {
                likes: db.command.inc(action === 'like' ? 1 : -1)
            }
        })

        // 更新tipLikes集合中的记录
        if (action === 'like') {
            await db.collection('tipLikes').add({
                data: {
                    tipId: tipId,
                    openid: wxContext.OPENID,
                    createTime: db.serverDate()
                }
            })
        } else {
            await db.collection('tipLikes')
                .where({
                    tipId: tipId,
                    openid: wxContext.OPENID
                })
                .remove()
        }

        // 获取更新后的点赞数
        const tipRes = await db.collection('tips').doc(tipId).get()

        return {
            code: 0,
            data: {
                likes: tipRes.data.likes
            }
        }
    } catch (err) {
        console.error('操作点赞失败:', err)
        return {
            code: -1,
            message: '操作失败'
        }
    }
}